<?php

//首页金刚区分类
namespace App\Http\Controllers\Admin\Mall;


use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Response\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class IndexCateController extends BaseController
{
    /**
     * @api {Get} /mall/index-product-cate/list 分类列表
     *
     * @apiGroup 个性商城-首页金刚区
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": [
    {
    "id": 6, 序号
    "title": "全部", 名称
    "icon": "", 图标url
    "is_show": 1 是否显示：1：是；0：否
    },
    ]
    }
     */
    public function list()
    {
        $list = app('model_mall_categories')
            ->select('id', 'title', 'icon', 'is_show', 'sort')
            ->where('parent_id', 0)
            ->orderBy('sort', 'asc')
            ->get();
        return Response::sendData($list);
    }

    /**
     * @api {Post} /mall/index-product-cate/add 添加分类
     *
     * @apiGroup 个性商城-首页金刚区
     *
     * @apiParam {String} cate_name 分类名称，必须
     * @apiParam {String} icon 图标url，必须
     * @apiParam {Int} is_show 是否显示：1：是；0：否，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[]}
     */
    public function add(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'cate_name' => 'required|string|max:10',
                'icon' => 'required|url',
                'is_show' => 'required|integer|in:1,0',
            ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $cateName = $request->cate_name;
        $icon = $request->icon;
        $isShow = $request->is_show;
        $sort = $request->input('sort', 0);

        $cate = app('model_mall_categories')->where('title', $cateName)->first();
        if ($cate) throw new BasicException(0, '分类名称已经存在');

        $res = app('model_mall_categories')->insert([
            'parent_id' => 0,
            'title' => $cateName,
            'icon' => $icon,
            'is_show' => $isShow,
            'sort' => $sort,
            'add_time' => time(),
        ]);
        if ($res) {
            return Response::sendData([]);
        } else {
            throw new BasicException(0, '添加失败');
        }
    }

    /**
     * @api {put} /mall/index-product-cate/edit 编辑分类
     *
     * @apiGroup 个性商城-首页金刚区
     *
     * @apiParam {Int} id 分类id，必须
     * @apiParam {String} cate_name 分类名称，必须
     * @apiParam {String} icon 图标url，必须
     * @apiParam {Int} is_show 是否显示：1：是；0：否，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[]}
     */
    public function edit(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'id' => 'required|integer|min:1',
                'cate_name' => 'required|string|max:10',
                'icon' => 'required|url',
                'is_show' => 'required|integer|in:1,0',
            ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());
        $sort = $request->input('sort', 0);

        $id = $request->id;
        $cateName = $request->cate_name;
        $icon = $request->icon;
        $isShow = $request->is_show;

        $cate = app('model_mall_categories')->where('title', $cateName)->where('id', '<>', $id)->first();
        if ($cate) throw new BasicException(0, '分类名称已经存在');

        $res = app('model_mall_categories')->where('id', $id)->update([
            'parent_id' => 0,
            'title' => $cateName,
            'icon' => $icon,
            'sort' => $sort,
            'is_show' => $isShow,
        ]);
        if ($res) {
            return Response::sendData([]);
        } else {
            throw new BasicException(0, '编辑失败');
        }
    }

    /**
     * @api {delete} /mall/index-product-cate/del 删除分类
     *
     * @apiGroup 个性商城-首页金刚区
     *
     * @apiParam {String} ids 分类id，多个用英文逗号连接，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[]}
     */
    public function del(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'ids' => 'required|string',
            ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $ids = explode(',', $request->ids);

        DB::beginTransaction();
        try {
            foreach ($ids as $id) {
                $cate = app('model_mall_categories')->where('id', $id)->first();
                if (empty($cate)) {
                    throw new BasicException(0, '分类id错误');
                }
                $product = app('model_mall_products')->select('id')->where('category_id', $id)->first();
                if ($product) {
                    throw new BasicException(0, '分类下还有商品，无法删除');
                }

                //删除分类
                $cate->delete();

                //删除分类与子分类的关联
                app('model_mall_category_join')->where('category_id', $id)->delete();
            }
            DB::commit();
            return Response::sendData([]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $e->getMessage());
        }
    }

    /**
     * @api {Get} /mall/index-product-cate/list-new 金刚区分类列表（v3.6）
     *
     * @apiGroup 个性商城-首页金刚区
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": [
    {
    "id": 6, 序号
    "title": "全部", 名称
    "icon": "", 图标url
    "is_show": 1 是否显示：1：是；0：否
    },
    ]
    }
     */
    public function listNew()
    {
        $list = app('model_mall_categories')->getCategories();
        return Response::sendData($list);
    }

    /**
     * @api {Post} /mall/index-product-cate/add-new 添加分类（v3.6）
     *
     * @apiGroup 个性商城-首页金刚区
     *
     * @apiParam {String} cate_name 分类名称，必须
     * @apiParam {String} icon 图标url，必须
     * @apiParam {Int} is_show 是否显示：1：是；0：否，必须
     * @apiParam {Int} sort 排序号，升序排列，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[]}
     */
    public function addNew(Request $request)
    {
        $param = $request->only('cate_name', 'icon', 'is_show', 'sort');
        $v = app('validator')->make($param, [
            'cate_name' => 'required|string|max:10',
            'icon' => 'required|url|max:255',
            'is_show' => 'required|integer|in:1,0',
            'sort' => 'required|integer|min:0|max:65535',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        app('repo_mall_categories')->addOrEditIndexCate($param);
        return Response::sendData([]);
    }

    /**
     * @api {put} /mall/index-product-cate/edit-new 编辑分类（v3.6）
     *
     * @apiGroup 个性商城-首页金刚区
     *
     * @apiParam {Int} id 分类id，必须
     * @apiParam {String} cate_name 分类名称，必须
     * @apiParam {String} icon 图标url，必须
     * @apiParam {Int} is_show 是否显示：1：是；0：否，必须
     * @apiParam {Int} sort 排序号，升序排列，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[]}
     */
    public function editNew(Request $request)
    {
        $param = $request->only('id', 'cate_name', 'icon', 'is_show', 'sort');
        $v = app('validator')->make($param, [
            'id' => 'required',
            'cate_name' => 'required|string|max:10',
            'icon' => 'required|url|max:255',
            'is_show' => 'required|integer|in:1,0',
            'sort' => 'required|integer|min:0|max:65535',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        app('repo_mall_categories')->addOrEditIndexCate($param);
        return Response::sendData([]);
    }
}